const {existsSync, readdirSync, statSync} = require('fs')
const {resolve, join} = require('path')
const {inspect} = require('util')
/**
 * 循环引用问题
 */
let b = {}
let a = {child: b}
b.parent = a

let c = {name: 'mal', age: 11}

function circular(obj) {
  let cache = new WeakMap()
  return (function derez(value, path){
    var temp;
    if (
      typeof value === 'object' &&
      (value !== null) &&
      !(value instanceof String) &&
      !(value instanceof RegExp) &&
      !(value instanceof Date) &&
      !(value instanceof Symbol)
    ) {
      // 校验是否存在该对象
      if (cache.has(value)) {
        return {$ref: path}
      }

      cache.set(value, path)

      if (Array.isArray(value)) {
        temp = []
        for (let i in value) {
          temp[i] = derez(value[i], path + '[' + i + ']')
        }
      } else {
        temp = {}
        for (let key in value) {
          temp[key] = derez(value[key], path + '[' + JSON.stringify(key) + ']')
        }
      }

      return temp
    } else {
      return value
    }
  })(obj, '$')
}

// console.log(circular(b))

// 递归生成文件树 {path, isDir, children: []}
function genFileTree (source) {
  if (!existsSync(source)) {
    console.log('源文件不存在')
    return
  }
  if (statSync(source).isDirectory()) {
    const data = {path: source, isDir: true, children: []}
    const allPath = readdirSync(source)
    for (let filepath of allPath) {
      filepath = join(source, filepath)
      if (statSync(filepath).isDirectory()) {
        data.children.push(genFileTree(filepath))
      } else {
        data.children.push({path: filepath, isDir: false})
      }
    }
    return data
  } else {
    return {path: source, isDir: false}
  }
}

// const source = resolve(__dirname, './test')
// console.log(inspect(genFileTree(source), false, 10))
